package com.github.permissiondog.cancanpbackend.servlet;

import com.github.permissiondog.cancanpbackend.model.User;
import com.github.permissiondog.cancanpbackend.response.BaseResponse;
import com.github.permissiondog.cancanpbackend.response.NavResponse;
import com.github.permissiondog.cancanpbackend.response.UserResponse;
import com.github.permissiondog.cancanpbackend.service.UserService;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "NavServlet", value = "/nav")
public class NavServlet extends BaseServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Integer uid = (Integer) request.getSession().getAttribute("uid");
        if (uid == null) {
            json(response, NavResponse.builder().ok(true).isLoggedIn(false).build());
            return;
        }
        User user = UserService.getInstance().getUserById(uid);
        if (user == null) {
            request.getSession().removeAttribute("uid");
            json(response, NavResponse.builder().ok(true).isLoggedIn(false).build());
            return;
        }
        json(response, NavResponse.builder().ok(true).isLoggedIn(true).user(user).build());
    }
}
